package com.ruoyi.common.constant;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Component
public class AllRequestMapping implements ApplicationRunner {
	
	private static List<String> urls = new ArrayList<String>();
	
	@Autowired
	WebApplicationContext applicationContext;
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		urls();
	}
	
	public boolean isSystemUrl(String url) {
		if(urls.contains(url)) {
			return true;
		}
		return false;
	}
	
	public boolean isSystemUrl(HttpServletRequest request) {
		if(urls.contains(request.getRequestURI())) {
			return true;
		}
		return false;
	}
	
	private List<String> urls() {
		if(CollectionUtils.isNotEmpty(urls)) {
			return urls;
		}else {
			RequestMappingHandlerMapping mapping = applicationContext
					.getBean(RequestMappingHandlerMapping.class);
			// 获取url与类和方法的对应信息
			Map<RequestMappingInfo, HandlerMethod> map = mapping
					.getHandlerMethods();
			for (RequestMappingInfo info : map.keySet()) {
				// 获取url的Set集合，一个方法可能对应多个url
				Set<String> patterns = info.getPatternsCondition().getPatterns();
				for (String url : patterns) {
					//把结果存入静态变量中程序运行一次次方法之后就不用再次请求次方法
					urls.add(url);
				}
			}
			return urls;
		}
	}
}